import Cocoa
import SwiftUI
import WallpaperLibrary

@available(macOS 12.0, *)
class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate {
    func windowWillClose(_ notification: Notification) {
        if let closingWindow = notification.object as? NSWindow,
           closingWindow === resourceLibraryWindow {
            resourceLibraryWindow = nil
        }
    }
    var window: NSWindow!
    var statusBarItem: NSStatusItem!
    var popover: NSPopover!
    weak var resourceLibraryWindow: NSWindow?
    
    func applicationDidFinishLaunching(_ aNotification: Notification) {
        // 创建主窗口
        let contentView = ContentView()
        
        window = NSWindow(
            contentRect: NSRect(x: 0, y: 0, width: 580, height: 680),
            styleMask: [.titled, .closable, .miniaturizable, .resizable],
            backing: .buffered, 
            defer: false)
        window.isMovableByWindowBackground = true
        window.center()
        window.setFrameAutosaveName("Main Window")
        window.contentView = NSHostingView(rootView: contentView)
        
        // 创建状态栏菜单
        setupStatusBar()
    }
    
    private func setupStatusBar() {
        statusBarItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
        
        if let button = statusBarItem.button {
            button.image = NSImage(systemSymbolName: "photo", accessibilityDescription: "壁纸设置工具")
        }
        
        let menu = NSMenu()
        
        menu.addItem(NSMenuItem(title: "打开主窗口", action: #selector(openMainWindow), keyEquivalent: ""))
        menu.addItem(NSMenuItem(title: "设置壁纸", action: #selector(setWallpaper), keyEquivalent: ""))
        
        menu.addItem(NSMenuItem(title: "恢复默认壁纸", action: #selector(resetWallpaper), keyEquivalent: ""))
        menu.addItem(NSMenuItem(title: "静音", action: #selector(toggleMute), keyEquivalent: "m"))
        menu.addItem(NSMenuItem.separator())
        menu.addItem(NSMenuItem(title: "退出", action: #selector(NSApplication.shared.terminate), keyEquivalent: "q"))
        
        statusBarItem.menu = menu
    }
    
    @objc func openMainWindow() {
        if window == nil {
            // 重新创建窗口
            let contentView = ContentView()
            window = NSWindow(
                contentRect: NSRect(x: 0, y: 0, width: 580, height: 680),
                styleMask: [.titled, .closable, .miniaturizable, .resizable],
                backing: .buffered, 
                defer: false)
            window.isMovableByWindowBackground = true
            window.center()
            window.setFrameAutosaveName("Main Window")
            window.contentView = NSHostingView(rootView: contentView)
        }
        window.makeKeyAndOrderFront(nil)
        NSApp.activate(ignoringOtherApps: true)
    }
    
    @objc func setWallpaper() {
        let panel = NSOpenPanel()
        panel.allowedContentTypes = [.image, .mpeg4Movie, .quickTimeMovie]
        panel.beginSheetModal(for: NSApp.keyWindow ?? window) { [weak self] response in
            guard let self = self else { return }
            guard response == .OK, let url = panel.url else { return }
            
            Task {
                do {
                    // 先添加到资源库
                    try await WallpaperLibrary.shared.addResource(url)
                    // 然后设置为壁纸
                    let isVideo = url.pathExtension.lowercased() == "mp4" || url.pathExtension.lowercased() == "mov"
                    try WallpaperManager.setWallpaper(with: url, isVideo: isVideo)
                    
                    await MainActor.run {
                        let alert = NSAlert()
                        alert.messageText = "设置成功"
                        alert.informativeText = "壁纸已更新"
                        alert.beginSheetModal(for: self.window) { _ in }
                    }
                } catch {
                    await MainActor.run {
                        let alert = NSAlert()
                        alert.messageText = "设置失败"
                        alert.informativeText = error.localizedDescription
                        alert.beginSheetModal(for: self.window) { _ in }
                    }
                }
            }
        }
    }
    
    @objc func resetWallpaper() {
        do {
            try WallpaperManager.resetWallpaper()
            DispatchQueue.main.async { [weak self] in
                guard let self = self else { return }
                let alert = NSAlert()
                alert.messageText = "成功"
                alert.informativeText = "已恢复默认壁纸"
                alert.beginSheetModal(for: self.window) { _ in }
            }
        } catch {
            DispatchQueue.main.async { [weak self] in
                guard let self = self else { return }
                let alert = NSAlert()
                alert.messageText = "失败"
                alert.informativeText = error.localizedDescription
                alert.beginSheetModal(for: self.window) { _ in }
            }
        }
    }
    
    @objc func toggleMute() {
        WallpaperManager.toggleMute()
        updateMuteMenuItem()
        NotificationCenter.default.post(name: .muteStateChanged, object: nil)
    }
    
    private func updateMuteMenuItem() {
        guard let menu = statusBarItem.menu else { return }
        if let muteItem = menu.item(withTitle: "静音") {
            muteItem.title = WallpaperManager.isMuted() ? "恢复声音" : "静音"
        }
    }
    
    
}
